package com.aq.syn;

/**
 * 不安全的买票 有负数
 */
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket station = new BuyTicket();
        new Thread(station, "苦逼的我").start();
        new Thread(station, "牛逼的你").start();
        new Thread(station, "可恶黄牛党").start();
    }

}

class BuyTicket implements Runnable {

    private int ticketNumbers = 10;
    private boolean flag = true; // 外部停止方式

    @Override
    public void run() {
        // 买票
        while (flag) {
            buy();
        }
    }

    // synchronized 变成 同步方法,锁的是 this
    private synchronized void buy() {
        // 判断是否有票
        if (ticketNumbers <= 0) {
            flag = false;
            return;
        }

        // 模拟延时
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(Thread.currentThread().getName() + "拿到了第：" + ticketNumbers-- + "张票");
    }

}
